//
//  QSFNetManager.m
//  QSF_Dev
//
//  Created by Mr.Dynasty on 2018/5/24.
//  Copyright © 2018年 Mr.Dynasty. All rights reserved.
//

#import "NetManager.h"
#import "UIAlertView+Block.h"

@implementation NetManager

+ (instancetype)shareManager {
    static NetManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[[self class] alloc] initWithBaseURL:nil];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript",@"text/css", nil];
        manager.requestSerializer.timeoutInterval = 60 * 5;
    });
    return manager;
}

/**
 设置请求头
 */
- (void)setupRequestHeader {
    
}

/**
 配置通用参数
 */
- (void)setupCommonParams:(NSDictionary *)dic {
    
}

- (NSURLSessionDataTask *)getWithUrl:(NSString *)urlString params:(NSDictionary *)params success:(QSFRequestSuccessBlock)success failure:(QSFRequestFailureBlock)failure {
    [self setupRequestHeader];
    NetReponseModel *reponseModel = [[NetReponseModel alloc] init];
    reponseModel.url = urlString;
    reponseModel.method = urlString;
    reponseModel.isPost = NO;
    reponseModel.paramDic = params;
    
    return [self GET:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self doWithSuccess:success failure:failure responseObject:responseObject responseModel:reponseModel];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self doWithFailure:failure errorStr:error.description reponseModel:reponseModel];
    }];
}

- (void)postWithUrl:(NSString *)urlString params:(NSDictionary *)params success:(QSFRequestSuccessBlock)success failure:(QSFRequestFailureBlock)failure {
    [self setupRequestHeader];
    
    NetReponseModel *reponseModel = [[NetReponseModel alloc] init];
    reponseModel.url = urlString;
    reponseModel.method = urlString;
    reponseModel.isPost = YES;
    reponseModel.paramDic = params;
    
    [self POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self doWithSuccess:success failure:failure responseObject:responseObject responseModel:reponseModel];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self doWithFailure:failure errorStr:error.description reponseModel:reponseModel];
    }];
}

- (void)uploadImageWithUrl:(NSString *)urlString params:(NSDictionary *)params success:(QSFRequestSuccessBlock)success failure:(QSFRequestFailureBlock)failure {
    NetReponseModel *reponseModel = [[NetReponseModel alloc] init];
    reponseModel.url = urlString;
    reponseModel.method = urlString;
    reponseModel.isPost = YES;
    reponseModel.paramDic = params;
    [self POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = params[@"file"];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self doWithSuccess:success failure:failure responseObject:responseObject responseModel:reponseModel];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self doWithFailure:failure errorStr:error.description reponseModel:reponseModel];
    }];
}

- (void)patchWithUrl:(NSString *)urlString params:(NSDictionary *)params success:(QSFRequestSuccessBlock)success failure:(QSFRequestFailureBlock)failure {
    [self setupRequestHeader];
    
    NetReponseModel *reponseModel = [[NetReponseModel alloc] init];
    reponseModel.url = urlString;
    reponseModel.method = urlString;
    reponseModel.isPost = YES;
    reponseModel.paramDic = params;
    
    [self PATCH:urlString parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self doWithSuccess:success failure:failure responseObject:responseObject responseModel:reponseModel];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self doWithFailure:failure errorStr:error.description reponseModel:reponseModel];
    }];
}

- (void)doWithSuccess:(QSFRequestSuccessBlock)success
              failure:(QSFRequestFailureBlock)failure
       responseObject:(id)responseObject
        responseModel:(NetReponseModel *)responseModel {
    HttpResponse *response = [HttpResponse yy_modelWithJSON:responseObject];
    
    responseModel.responseDic = response.data;
    responseModel.result = response.code;
    responseModel.reponseMessage = response.msg;
    [responseModel printRequestLog];
    
    if (response.code == 1000 || response.code == 0) {
        if (success) {
            success(response.data);
            return;
        }
    }
    else
    {
        if (failure) {
            failure(response.msg);
            return;
        }
    }
}

- (void)doWithFailure:(QSFRequestSuccessBlock)failure
             errorStr:(NSString *)errorStr
         reponseModel:(NetReponseModel *)reponseModel {
    errorStr = @"当前网络状态不佳，请检查本地网络";
    if (failure) {
        failure(errorStr);
    }
    reponseModel.responseDic = nil;
    reponseModel.result = NO;
    reponseModel.reponseMessage = errorStr;
    [reponseModel printRequestLog];
}


@end
